package com.ruoyi.forum.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.forum.domain.vo.ForumUpdateEmail;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.forum.domain.ForumStudent;
import com.ruoyi.forum.service.IForumStudentService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 学生管理Controller
 * 
 * @author ruoyi
 * @date 2024-02-02
 */
@RestController
@RequestMapping("/forum/student")
public class ForumStudentController extends BaseController
{
    @Autowired
    private IForumStudentService forumStudentService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询学生管理列表
     */
    @PreAuthorize("@ss.hasPermi('forum:student:list')")
    @GetMapping("/list")
    public TableDataInfo list(ForumStudent forumStudent)
    {
        startPage();
        if(forumStudent.getDelFlag()==null){
            forumStudent.setDelFlag("0");
        }
        List<ForumStudent> list = forumStudentService.selectForumStudentList(forumStudent);
        return getDataTable(list);
    }

    /**
     * 导出学生管理列表
     */
    @PreAuthorize("@ss.hasPermi('forum:student:export')")
    @Log(title = "学生管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ForumStudent forumStudent)
    {
        List<ForumStudent> list = forumStudentService.selectForumStudentList(forumStudent);
        ExcelUtil<ForumStudent> util = new ExcelUtil<ForumStudent>(ForumStudent.class);
        util.exportExcel(response, list, "学生管理数据");
    }

    /**
     * 获取学生管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('forum:student:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(forumStudentService.selectForumStudentById(id));
    }

    /**
     * 新增学生管理
     */
    @PreAuthorize("@ss.hasPermi('forum:student:add')")
    @Log(title = "学生管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ForumStudent forumStudent)
    {
        //根据学生信息构建系统用户对象
        SysUser user = new SysUser();
        user.setUserId(forumStudent.getStudentId());
        user.setUserName(forumStudent.getStudentName());
        user.setNickName(forumStudent.getNickName());
        user.setEmail(forumStudent.getEmail());
        user.setPhonenumber(forumStudent.getPhonenumber());
        user.setSex(forumStudent.getSex());
        user.setAvatar(forumStudent.getAvatar());
        user.setStatus(forumStudent.getStatus());
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        forumStudent.setDeptId(200l);
        forumStudent.setCreateBy(getUsername());
        forumStudent.setPassword(SecurityUtils.encryptPassword(forumStudent.getPassword()));
        return toAjax(forumStudentService.insertForumStudent(forumStudent));
    }

    /**
     * 修改学生管理
     */
    @PreAuthorize("@ss.hasPermi('forum:student:edit')")
    @Log(title = "学生管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ForumStudent forumStudent)
    {
        SysUser user = new SysUser();
        user.setUserId(forumStudent.getStudentId());
        user.setUserName(forumStudent.getStudentName());
        user.setNickName(forumStudent.getNickName());
        user.setSex(forumStudent.getSex());
        user.setPhonenumber(forumStudent.getPhonenumber());
        user.setEmail(forumStudent.getEmail());
        user.setAvatar(forumStudent.getAvatar());
        user.setStatus(forumStudent.getStatus());
        user.setDelFlag(forumStudent.getDelFlag());
        user.setRemark(forumStudent.getRemark());
        user.setCreateBy(forumStudent.getCreateBy());
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        List<Long> longs = roleService.selectRoleListByUserId(user.getUserId());
        boolean isStudent = false;
        for(long roleid:longs){
            if(roleid == 100L){
                isStudent = true;
            }
        }
        if(!isStudent){
            return error("修改学生'" + user.getUserName() + "'失败，该学生不存在");
        }
        if (!userService.checkUserNameUnique(user))
        {
//            return error("修改学生'" + user.getUserName() + "'失败，该账号名已存在");
            return popup("修改失败,账号名已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
//            return error("修改学生'" + user.getUserName() + "'失败，手机号码已存在");
            return popup("修改失败,手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
//            return error("修改学生'" + user.getUserName() + "'失败，邮箱账号已存在");
            return popup("修改失败,邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(forumStudentService.updateForumStudent(forumStudent));
    }

    /**
     * 修改学生密码管理
     */
    @PreAuthorize("@ss.hasPermi('forum:student:resetPwd')")
    @Log(title = "学生管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody ForumStudent forumStudent)
    {
        if(forumStudent.getPassword()==null&&"".equals(forumStudent.getPassword())){
            return error("修改学生'" + forumStudent.getStudentName() + "'密码失败，未输入密码不存在");
        }
        forumStudent.setPassword(SecurityUtils.encryptPassword(forumStudent.getPassword()));
        SysUser user = new SysUser();
        user.setUserId(forumStudent.getStudentId());
        user.setUserName(forumStudent.getStudentName());
        user.setPassword(forumStudent.getPassword());
        //查看是否允许用户
        userService.checkUserAllowed(user);
        //查看用户是否有该数据权限
        userService.checkUserDataScope(user.getUserId());
        //查看修改的用户是否是学生角色
        List<Long> longs = roleService.selectRoleListByUserId(user.getUserId());
        boolean isStudent = false;
        for(long roleid:longs){
            if(roleid == 100L){
                isStudent = true;
            }
        }
        if(!isStudent){
            return error("修改学生'" + user.getUserName() + "'密码失败，该学生不存在");
        }
        user.setUpdateBy(getUsername());
        //前往service层修改用户密码
        return toAjax(forumStudentService.updateForumStudentPassword(forumStudent));
    }

    /**
     * 测试邮箱验证码是否正确
     */
    @PreAuthorize("@ss.hasPermi('forum:student:checkCode')")
    @Log(title = "学生管理", businessType = BusinessType.UPDATE)
    @PostMapping("/checkCode")
    public AjaxResult checkEmailCode(@Valid @RequestBody ForumUpdateEmail forumUpdateEmail)
    {
        Object cacheObject = redisCache.getCacheObject(forumUpdateEmail.getEmail());
        if(cacheObject!=null){
            String redisCode = (String) cacheObject;
            if(!redisCode.equals(forumUpdateEmail.getCode())){
                return popup("邮箱验证码不正确");
            }
        }else {
            return popup("邮箱验证码已失效。提示：验证码只有2分钟时效。");
        }

        return success("邮箱验证码，验证成功。");
    }

    /**
     * 修改学生邮箱
     */
    @PreAuthorize("@ss.hasPermi('forum:student:resetEmail')")
    @Log(title = "学生管理", businessType = BusinessType.UPDATE)
    @PostMapping("/resetEmail")
    public AjaxResult resetEmail(@Valid @RequestBody ForumUpdateEmail forumUpdateEmail)
    {
        if(forumUpdateEmail.getId()==null ){
            return popup("用户ID不能为空");
        }
        Object cacheObject = redisCache.getCacheObject(forumUpdateEmail.getEmail());
        if(cacheObject!=null){
            String redisCode = (String) cacheObject;
            if(!redisCode.equals(forumUpdateEmail.getCode())){
                return popup("邮箱验证码不正确");
            }
        }else {
            return popup("邮箱验证码已失效。提示：验证码只有2分钟时效。");
        }
        ForumStudent forumStudent = new ForumStudent();
        forumStudent.setStudentId(forumUpdateEmail.getId());
        forumStudent.setEmail(forumUpdateEmail.getEmail());
//        forumStudentService.updateForumStudent(forumStudent);
        //前往service层修改用户密码
        return toAjax(forumStudentService.updateForumStudent(forumStudent));
    }

    /**
     * 删除学生管理
     */
    @PreAuthorize("@ss.hasPermi('forum:student:remove')")
    @Log(title = "学生管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for(long id : ids){
            List<Long> longs = roleService.selectRoleListByUserId(id);
            boolean isStudent = false;
            for(long roleid:longs){
                if(roleid == 100L){
                    isStudent = true;
                }
            }
            if(!isStudent){
                return error("修改学生'" + id + "'失败，该学生不存在");
            }
        }
        return toAjax(forumStudentService.deleteForumStudentByIds(ids));
    }
}
